package com.geek.controller;


import com.geek.bean.BaseRespVo;
import com.geek.model.MarketStorage;
import com.geek.service.StorageService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author 小豪
 * @version 1.0
 * @description 文件上传
 * @date 2024-06-17 18:56
 */
@RestController
@RequestMapping("/wx/storage")
public class WxStorageController {

    @Autowired
    private StorageService storageService;
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucketName}")
    private String bucketName;

    @PostMapping("/upload")
    public BaseRespVo upload(MultipartFile file) {
        // 上传文件
        try {
            String originalFilename = file.getOriginalFilename();
            String fileName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String objectName = uuid + "." + fileName;
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build());
            MarketStorage marketStorage = storageService.upload(file, objectName);
            return BaseRespVo.ok(marketStorage);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
